package com.alageek.personalblog.common.util;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * MarkDown工具类
 * @author AlaGeek
 */
public class MarkdownUtils {

    /**
     * Markdown转HTML文本
     * @param markdown Markdown文本
     * @return HTML文本
     */
    public static String markdownToHtml(String markdown){
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * Markdown转HTML文本【带扩展：标题锚点；表格生成】
     * @param markdown Markdown文本
     * @return HTML文本
     */
    public static String markdownToHtmlExtensions(String markdown){
        // h标签生成id
        Set<Extension> headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create());
        // 转换table的HTML
        List<Extension> tableExtensions = Collections.singletonList(TablesExtension.create());
        Parser parser = Parser.builder()
                .extensions(tableExtensions)
                .build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(headingAnchorExtensions)
                .extensions(tableExtensions)
                .attributeProviderFactory(attributeProviderContext -> new CustomAttributeProvider())
                .softbreak("<br>")
                .build();
        return renderer.render(document);
    }

    /**
     * 处理标签的属性
     */
    static class CustomAttributeProvider implements AttributeProvider{
        @Override
        public void setAttributes(Node node, String tagName, Map<String, String> attributes) {
            // 改变a标签的target属性为_blank
            if(node instanceof Link){
                attributes.put("target", "_blank");
            }
            if(node instanceof TableBlock){
                attributes.put("class", "ui celled table");
            }
        }
    }

    public static void main(String[] args) {
        String markdown = ">K = 1, N = 2\r\n>K = 2, N = 6\r\n>K = 3, N = 14";
        String html = markdownToHtmlExtensions(markdown);
        System.out.println(html);
    }

}
